package com.lagou.impl;

import com.lagou.PlayManager;
import com.lagou.Player;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mcl
 * @date 2021/12/29 14:04
 * @description
 */
public class LagouPlayManager implements PlayManager {

    private Map<String,Player> playerMap = new ConcurrentHashMap();

    private static LagouPlayManager instance = new LagouPlayManager();

    public static LagouPlayManager getInstance() {
        return instance;
    }

    private LagouPlayManager() {
    }

    @Override
    public void addPlayer(Player player) {
        System.out.println("Player ".concat(player.getUsername()).concat(" joined."));
        playerMap.put(player.getUsername(),player);
    }

    @Override
    public Player getPlayer(String username) {
        return playerMap.get(username);
    }

    @Override
    public void broadcast(String message) {
        playerMap.forEach((s, player) -> {
            player.write(message);
        });
    }

    @Override
    public void removeOfflinePlayer() {
        System.out.println("check offline players");
        List<Player> offlinePlayers = new ArrayList<>();
        playerMap.forEach((s, player) -> {
            if (player.isOffline()) {
                offlinePlayers.add(player);
            }
        });
        System.out.println("offline users count: ".concat(String.valueOf(offlinePlayers.size())));
        offlinePlayers.forEach(player -> {
            playerMap.remove(player.getUsername());
        });
    }
}
